package com.herui.ota.service.iml;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.herui.ota.dao.mysql.DeviceOtaMapper;
import com.herui.ota.entity.DeviceOta;
import com.herui.ota.entity.DeviceOtaSoft;
import com.herui.ota.enums.OpsTypeEnum;
import com.herui.ota.enums.ResponseEnum;
import com.herui.ota.exception.ServiceException;
import com.herui.ota.pojo.form.DeviceOtaFilterForm;
import com.herui.ota.service.DeviceOtaService;
import com.herui.ota.service.DeviceOtaTreeService;
import com.herui.ota.service.OpsRecordService;
import com.mlnx.common.form.PageForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author name: amanda.shan
 * create time: 2023-10-26 13:19:07
 */ 
@Service
public class DeviceOtaServiceIml extends BaseService<DeviceOtaMapper, DeviceOta> implements DeviceOtaService{

	@Autowired
	private DeviceOtaTreeService deviceOtaTreeService;

	@Autowired
	private OpsRecordService opsRecordService;


	@Autowired
	@Override
	public void setBaseMapper(DeviceOtaMapper baseMapper) {
		super.setBaseMapper(baseMapper);
	}

	@PostConstruct
	public void init(){
		resetTree();
	}

	@Override
	public IPage page(PageForm pageForm, Object filter) throws IllegalAccessException {

		QueryWrapper<DeviceOta> queryWrapper = new QueryWrapper<>();

		DeviceOtaFilterForm filterForm = (DeviceOtaFilterForm) filter;
		List<String> treeFilters = filterForm.getTreeFilter();
		if (treeFilters != null && treeFilters.size() > 0){
			queryWrapper.and(wrapper -> {
				for (String treeFilter: treeFilters){
					wrapper.or(queryWrapper1 -> {
						String[] split = treeFilter.split("-");
						String[] keys = {"brand", "print_type", "market", "series"};
						for (int i = 0; i < split.length && i < keys.length ; i++) {
							queryWrapper1.eq(keys[i], split[i]);
						}
					});
				}
			});

		}

		if (!StringUtils.isEmpty(filterForm.getState())){
			queryWrapper.eq("state", filterForm.getState());
		}

		queryWrapper.orderByDesc("create_time");

		IPage page = page(new Page(pageForm.getCurrent(), pageForm.getSize()), queryWrapper);
		return page;
	}

	@Transactional
	@Override
	public void save(DeviceOta entity) {

		checkRight("soft_rightota");

		super.save(entity);

		String treeInfo = entity.getTreeInfo();
		deviceOtaTreeService.saveTree(treeInfo);

		opsRecordService.save(OpsTypeEnum.CREATE_OTA, entity.getId(), JSON.toJSONString(entity));
	}

	@Transactional
	@Override
	public boolean updateById(DeviceOta entity) {

		checkRight("soft_rightota");

		boolean b = false;
//		UpdateStateEnum updateState = entity.getUpdateState();
//		if (updateState != null && updateState.equals(UpdateStateEnum.ENABLE)){
//			DeviceOta deviceOta = new DeviceOta();
//			deviceOta.setUpdateState(UpdateStateEnum.DISABLE);
//			b = update(deviceOta, new QueryWrapper<DeviceOta>().eq("type", entity.getType()));
//		}else {
//			b = super.updateById(entity);
//		}

		DeviceOta oldDeviceOta = getById(entity.getId());
		b = super.updateById(entity);
		entity = getById(entity.getId());

		if (oldDeviceOta.isSame(entity)){
			String treeInfo = entity.getTreeInfo();
			deviceOtaTreeService.saveTree(treeInfo);
		}else{
			String treeInfo = entity.getTreeInfo();
			deviceOtaTreeService.saveTree(treeInfo);
//			deviceOtaTreeService.resetTree();
		}

		opsRecordService.save(OpsTypeEnum.UPDATE_OTA, entity.getId(), JSON.toJSONString(entity));
		return b;
	}

	@Override
	public boolean removeById(Serializable id) {
		checkRight("soft_rightota");
		DeviceOta deviceOta = getById(id);
		opsRecordService.save(OpsTypeEnum.DELETE_OTA, deviceOta.getId(), JSON.toJSONString(deviceOta));
		return super.removeById(id);
	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {

		checkRight("soft_rightota");
		idList.stream().forEach(id ->{
			DeviceOta deviceOta = getById(id);
			opsRecordService.save(OpsTypeEnum.DELETE_OTA, deviceOta.getId(), JSON.toJSONString(deviceOta));
		});

		return super.removeByIds(idList);
	}

	@Override
	public List<Object> list(Object filter) throws IllegalAccessException {

//		QueryWrapper<DeviceOta> queryWrapper = new QueryWrapper<>();
		DeviceOtaFilterForm filterForm = (DeviceOtaFilterForm) filter;
//		if (!StringUtils.isEmpty(filterForm.getSeries())){
//			queryWrapper.like("series", "%"+filterForm.getSeries()+"%");
//		}
		List<DeviceOta> list = baseMapper.listDeviceOta(filterForm);
		List<Object> collect = list.stream().map(deviceOta -> (Object) deviceOta).collect(Collectors.toList());

		return collect;
	}

	@Override
	public void otaOnline(Integer id) {
		DeviceOta deviceOta = new DeviceOta();
		deviceOta.setId(id);
		deviceOta.setState("ONLINE");
		super.updateById(deviceOta);

		deviceOta = getById(deviceOta.getId());
		String treeInfo = deviceOta.getTreeInfo();
		deviceOtaTreeService.saveTree(treeInfo);
	}

	@Override
	public void resetTree() {
		List<DeviceOta> list = list();
		List<String> collect = list.stream().map(deviceOta -> deviceOta.getTreeInfo()).collect(Collectors.toList());
		deviceOtaTreeService.resetAll(collect);
	}

	@Override
	public DeviceOta getDeviceOta(String brand, String market, String printType, String series) {
		DeviceOta deviceOta = getOne(new QueryWrapper<DeviceOta>().eq("brand", brand).eq("print_type", printType)
				.eq("market", market)
				.eq("series", series));
		return deviceOta;
	}

	@Override
	public List<DeviceOta> getDeviceOtas(String printType, String channel) {
		return null;
	}

}

